﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Business;
using NetDon.OA.Interface;
using NetDon.OA.Interface.eLogistics;
using NetDon.Utilities;
using NetDon.WebControls;

namespace NetDon.OA.Portal.Finance
{

    [Navigation("干线流程", "付款台帐管理")]

    [Function("eLogistics.PaymentMachineAccountInfoManagement")]
    [PageTabber(Index = 0, NavigateUrl = "~/Finance/PaymentMachineAccountInfoManagement.aspx", Title = "付款台帐管理", Type = typeof(PaymentMachineAccountInfoManagement))]
    [PageTabber(Index = 1, NavigateUrl = "~/Finance/DailyFinancialDetailsQuery.aspx", Title = "查询每日明细", Type = typeof(DailyFinancialDetailsQuery))]
    public partial class PaymentMachineAccountInfoManagement : NavigationPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                //btnSearchDailyFinancialDetails.Attributes.Add("onclick", "searchDailyFinancialDetails();return false;");
                PageQueryAdapter1.PageSize = 20;

              //  txtPaymentOrIncomeDateStart.Text =DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");
                txtPaymentOrIncomeDateEnd.Text =  DateTime.Now.ToString("yyyy-MM-dd");
                txtReceivingOrderDateStart.Text = DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");
                txtReceivingOrderDateEnd.Text = DateTime.Now.ToString("yyyy-MM-dd");
                ddlCompany.InsertEmptyItem(ListEmptyType.Select);
                if (!this.IsSuperRoles())
                {
                    ddlCompany.SelectedValue = CurrentApplicationContext.CompanyId.ToString();
                    ddlCompany.Enabled = false;
                }
                PageQueryAdapter1.PerformQuery();

            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            PageQueryAdapter1.PerformQuery();
        }



        protected void btnReload_Click(object sender, EventArgs e)
        {
            PageQueryAdapter1.ReloadCurrentPage();
        }


        protected void PageQueryAdapter1_PerformGetPageData(object sender, PerformGetPageDataEventArgs e)
        {

            var service = ServiceContainer.GetService<IIssuingOrderService>();
            e.DataSource = service.GetMachineAccountOrders((IssuingOrderSearchCriteria)e.Condition, gridOrderList.SortExpression,
                                                      gridOrderList.SortDirection, e.PageSize, e.PageIndex);

        }

        protected void PageQueryAdapter1_PerformGetRecordCount(object sender, PerformGetRecordCountEventArgs e)
        {
            var service = ServiceContainer.GetService<IIssuingOrderService>();
            e.RecordCount = service.GetGetMachineAccountOrdersCount((IssuingOrderSearchCriteria)e.Condition);

        }

        protected void PageQueryAdapter1_PerformGetCondition(object sender, PerformGetConditionEventArgs e)
        {
            e.Condition = IssuingOrderSearchCriteria();
        }


        private IssuingOrderSearchCriteria IssuingOrderSearchCriteria()
        {
            var criteria = new IssuingOrderSearchCriteria
            {

            };
            if (!MiscUtilities.IsNullOrEmpty(ddlCompany.SelectedValue))
            {
                criteria.AreaId = ddlCompany.SelectedValue.ToGuid();
            }

            if (!string.IsNullOrEmpty(txtOrderCode.Text))
            {
                criteria.OrderCode = txtOrderCode.Text.Trim();
            }

            if (!string.IsNullOrEmpty(txtTransportationPlanCode.Text))
            {
                criteria.TransportationPlanCode = txtTransportationPlanCode.Text.Trim();
            }

            if (!string.IsNullOrEmpty(ddlPaymentMethod.SelectedValue))
            {
                criteria.PaymentMethod = ddlPaymentMethod.SelectedValue.ToGuid();
            }
            if (!MiscUtilities.IsNullOrEmpty(ddlRouteTypeId.SelectedValue.ToGuid()))
            {
                criteria.RouteTypeId = ddlRouteTypeId.SelectedValue.ToGuid();
            }

            DateTime? dateStart = null, dateEnd = null;
            if (!string.IsNullOrEmpty(txtReceivingOrderDateStart.Text.Trim()))
            {
                dateStart = DateTime.Parse(txtReceivingOrderDateStart.Text.Trim());
            }
            if (!string.IsNullOrEmpty(txtReceivingOrderDateEnd.Text.Trim()))
            {
                dateEnd = DateTime.Parse(txtReceivingOrderDateEnd.Text.Trim());
            }
            if (dateStart.HasValue || dateEnd.HasValue)
            {
                criteria.ReceivingOrderDate = new Range<DateTime?>(dateStart, dateEnd);
            }

            return criteria;
        }

        private MachineAccountSearchCriteria GetSearchCriteira()
        {
            var criteria = new MachineAccountSearchCriteria
            {

            };
            if (!this.IsSuperRoles())
            {
                criteria.AreaId = (CurrentApplicationContext).CompanyId;
            }
            DateTime? dateStart = null, dateEnd = null;
            if (!string.IsNullOrEmpty(txtPaymentOrIncomeDateStart.Text.Trim()))
            {
                dateStart = DateTime.Parse(txtPaymentOrIncomeDateStart.Text.Trim());
            }
            if (!string.IsNullOrEmpty(txtPaymentOrIncomeDateEnd.Text.Trim()))
            {
                dateEnd = DateTime.Parse(txtPaymentOrIncomeDateEnd.Text.Trim());
            }
            if (dateStart.HasValue || dateEnd.HasValue)
            {
                criteria.PaymentOrIncomeDate = new Range<DateTime?>(dateStart, dateEnd);
            }

         
            if (!string.IsNullOrEmpty(txtOrderCode.Text))
            {
                criteria.OrderCode = txtOrderCode.Text.Trim();
            }

            if (!string.IsNullOrEmpty(txtTransportationPlanCode.Text))
            {
                criteria.TransportationPlanCode = txtTransportationPlanCode.Text.Trim();
            }

            if (!string.IsNullOrEmpty(ddlPaymentMethod.SelectedValue))
            {
                criteria.PaymentMethod = ddlPaymentMethod.SelectedValue.ToGuid();
            }
            if (!MiscUtilities.IsNullOrEmpty(ddlRouteTypeId.SelectedValue.ToGuid()))
            {
                criteria.RouteTypeId = ddlRouteTypeId.SelectedValue.ToGuid();
            }
            if (ckbIsMachineAccountIncome.Checked)
            {
                criteria.PaymentOrIncome = MachineAccountType.Income;
            }
            else if (ckbIsMachineAccountPayment.Checked)
            {
                criteria.PaymentOrIncome = MachineAccountType.Payment;
            }
            else if (ckbIsMachineAccountAll.Checked)
            {
                criteria.PaymentOrIncome = MachineAccountType.All;
            }
            return criteria;

        }

        protected void gridOrderList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var entity = (e.Row.DataItem);

                var orderId = e.Row.Attributes["Id"] = Convert.ToString(DataBinder.Eval(entity, "Id"));
                //var pendingShippCostObj = DataBinder.Eval(entity, "PendingShippingCost");
                //var pendingShippingCost =MiscUtilities.IsNullOrEmpty(pendingShippCostObj) ? 0  :Convert.ToDecimal(pendingShippCostObj);
                //if(pendingShippingCost <=0)
                //{

                //}
                var orderStatus = Convert.ToString(DataBinder.Eval(entity, "OrderStatus")).ToEnum<OrderStatus>();
                //var btnConfirmOrderClosure = (ImageButton)e.Row.FindControl("btnConfirmOrderClosure");
                //if (btnConfirmOrderClosure != null)
                //{
                //    btnConfirmOrderClosure.OnClientClick = string.Format("confirmOrderClosure('{0}');return false;", orderId);


                //    if (orderStatus != OrderStatus.ReceiptTrackComplted)
                //    {
                //        btnConfirmOrderClosure.Visible = false;
                //    }
                //}
                var btnCreateNew = (ImageButton)e.Row.FindControl("btnCreateNew");
                if (btnCreateNew != null)
                {
                    btnCreateNew.OnClientClick = string.Format("createIssuingOrderInfo('{0}');return false;", orderId);
                    if (!IsManager())
                    {
                        var revenueMachinAccount = ServiceContainer.GetService<IRevenueMachineAccountService>().GetRevenueMachineAccount(orderId.ToGuid());
                        if (revenueMachinAccount != null)
                        {
                            if (revenueMachinAccount.IsStatementofAccountCompleted)
                            {
                                btnCreateNew.Visible = false;
                            }
                        }

                    }

                }
            }
        }

        protected void grdOrderPayment_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var entity = (e.Row.DataItem);

                var orderId = e.Row.Attributes["Id"] = Convert.ToString(DataBinder.Eval(entity, "Id"));
                var paymentOrIncome = e.Row.Attributes["PaymentOrIncome"] = Convert.ToString(DataBinder.Eval(entity, "PaymentOrIncome"));

                var issuingOrderId =
                    e.Row.Attributes["IssuingOrderId"] = DataBinder.Eval(entity, "IssuingOrderId").ToString();

                var btnDetails = (ImageButton)e.Row.FindControl("btnDetails");
                if (btnDetails != null)
                {
                    btnDetails.OnClientClick = string.Format("modifyOrderPayment('{0}','{1}','{2}','{3}');return false;", orderId, paymentOrIncome, issuingOrderId, true);
                }
                var btnEdit = (ImageButton)e.Row.FindControl("btnEdit");
                if (btnEdit != null)
                {
                    btnEdit.OnClientClick = string.Format("modifyOrderPayment('{0}','{1}','{2}','{3}');return false;", orderId, paymentOrIncome, issuingOrderId ,false);
                }
                

                var btnDelete = (ImageButton)e.Row.FindControl("btnDelete");
                if (btnDelete != null)
                {
                    btnDelete.OnClientClick = string.Format("deleteOrder('{0}','{1}');return false;", orderId, paymentOrIncome);
                }

                var revenueMachinAccount = ServiceContainer.GetService<IRevenueMachineAccountService>().GetRevenueMachineAccount(issuingOrderId.ToGuid());
                if (revenueMachinAccount.IsStatementofAccountCompleted && !IsManager())
                {
                    if (btnDelete != null)
                    {
                        btnDelete.Visible = false;
                    }
                    if (btnEdit != null)
                    {
                        btnEdit.Visible = false;
                    }
                }
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            var orderId = fieldOrderId.Value.ToGuid();
            var service = ServiceContainer.GetService<IMachineAccountService>();
            var paymentOrIncome = EnumUtilities.Parse<MachineAccountType>(this.fieldpaymentOrIncome.Value);
            if (service.RemoveMachineAccounts(orderId, paymentOrIncome))
            {
                PageQueryAdapter1.ReloadCurrentPage();
                Alert("删除成功!");
            }
        }

        protected void btnSearchDailyFinancialDetails_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Finance/DailyFinancialDetailsQuery.aspx");
        }

        protected void btnHiddenConfirmOrderClosure_Click(object sender, EventArgs e)
        {
            var orderId = fieldOrderId.Value.ToGuid();
            var service = ServiceContainer.GetService<IIssuingOrderService>();
            if (!service.CheckIsPaymentExist(orderId))
            {
                Alert("该订单没有付款记录不可以结案!");
                return;
            }
            if (service.ConfirmOrderClosure(orderId))
            {
                PageQueryAdapter1.ReloadCurrentPage();
                Alert("订单结案成功!");
            }
        }

        protected void btnAutoConfirmOrderClosure_Click(object sender, EventArgs e)
        {
            var service = ServiceContainer.GetService<IIssuingOrderService>();
            if (service.AutoConfirmOrderClosure())
            {
                PageQueryAdapter1.ReloadCurrentPage();
                Alert("订单自动结案成功!");
            }
        }
        protected void gridProductList_RowDetailCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var issuingOrderId = gridOrderList.DataKeys[e.Row.RowIndex]["Id"].ToString().ToGuid();
                var service = ServiceContainer.GetService<IMachineAccountService>();
                var searchCriteria = GetSearchCriteira();
                searchCriteria.IssuingOrderId = issuingOrderId;
                grdOrderPayment.DataSource = service.SearchMachineAccountDataByCondition(searchCriteria);
                grdOrderPayment.DataBind();

            }
        }




    }
}